﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using SQLiteClient;
using CSKLiteWindowsPhone.Common;
using CSKLiteWindowsPhone.WebsiteData;
using Coding4Fun.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Threading;

namespace CSKLiteWindowsPhone
{
    public partial class TestProcedures : PhoneApplicationPage
    {
        SQLiteConnection _db = null;
        private WebsiteDataSoapClient _websiteDataClient;
        private string _token = string.Empty;
        private string _userName = string.Empty;

        private Timer refreshTimer;
        public TestProcedures()
        {
            InitializeComponent();
            this._db = Utility.GetConnection();
            this._token = IsolatedStorageSettings.ApplicationSettings[Constants.LoginTockenKey] as string;
            this._userName = IsolatedStorageSettings.ApplicationSettings[Constants.LoginUserNameKey] as string;

            this.Loaded += new RoutedEventHandler(TestCases_Loaded);
        }

        void TestCases_Loaded(object sender, RoutedEventArgs e)
        {
            SQLiteCommand cmd = this._db.CreateCommand("SELECT * FROM TestProcedure");
            IEnumerable<TestProcedure> tests = cmd.ExecuteQuery<TestProcedure>();

            this.reorderListBox.ItemsSource = tests;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.GetTestProcs();
        }

        private void GetTestProcs()
        {
            this._websiteDataClient = Utility.GetWebsiteDataSoapClient();
            this._websiteDataClient.GetTestProceduresAsync(this._token, this._userName);
            this._websiteDataClient.GetTestProceduresCompleted += new EventHandler<GetTestProceduresCompletedEventArgs>(_websiteDataClient_GetTestProceduresCompleted);
        }

        void _websiteDataClient_GetTestProceduresCompleted(object sender, GetTestProceduresCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                TestProceduresResponse resposne = e.Result;

                this.MaintainTestProcedures(resposne.TestProcedures);

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ToastPrompt toast = new ToastPrompt();
                    toast.Message = "Refresh succeeded";
                    toast.Show();
                });
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ToastPrompt toast = new ToastPrompt();
                    Array.ForEach(e.Result.Errors, new Action<Error>((err) => { toast.Message += err.Message; }));
                    toast.Show();
                });
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                this.refreshPanel.IsRefreshing = false;
            });
        }



        private void MaintainTestProcedures(TestProcedure[] procs)
        {
            if (this._db != null)
            {

                string sql = @"
CREATE TABLE IF NOT EXISTS TestProcedure (Id INTEGER PRIMARY KEY,
Code text,
Sequence text,
[Group] text,
ParameterType text,
Parameter text,
ResultCode text)";
                SQLiteCommand cmd = this._db.CreateCommand(sql);
                int i = cmd.ExecuteNonQuery();

                cmd = this._db.CreateCommand("DELETE FROM TestProcedure");
                cmd.ExecuteNonQuery();

                foreach (var item in procs)
                {
                    sql = string.Format(@"INSERT INTO TestProcedure(
Id,
Code,
Sequence,
[Group],
ParameterType,
Parameter,
ResultCode) VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')",
item.Id,
item.Code,
item.Sequence,
item.Group,
item.ParameterType,
item.Parameter,
item.ResultCode);
                    cmd = this._db.CreateCommand(sql);
                    cmd.ExecuteNonQuery();
                }

                cmd = this._db.CreateCommand("SELECT * FROM TestProcedure");
                IEnumerable<TestProcedure> tests = cmd.ExecuteQuery<TestProcedure>();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.reorderListBox.ItemsSource = tests;
                });
            }

        }

        private void refreshPanel_RefreshRequested(object sender, EventArgs e)
        {
            this.refreshPanel.IsRefreshing = true;
            this.refreshTimer = new Timer(
                delegate
                {
                    // Refresh the fake data!

                    this.GetTestProcs();

                },
                null, 3000, -1);
        }

    }
}